package com.ycl.javacore.algorithm;

import java.util.LinkedList;
import java.util.Queue;

/**
 * User: OF1089 杨成龙
 * Date: 2019/8/4
 * Time: 10:26 AM
 * Desc: 获取树的最小深度
 */
public class AlgoCast16Tree {
    public class TreeNode {
        private int val;
        private TreeNode left;
        private TreeNode right;

        public TreeNode(int val) {
            this.val = val;
        }
    }

    //递归调用
    public int minDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        if (root.left == null && root.right == null) {
            return 1;
        }
        if (root.left != null) {
            return minDepth(root.left) + 1;
        }
        if (root.right != null) {
            return minDepth(root.right) + 1;
        }
        return Math.min(minDepth(root.left), minDepth(root.right)) + 1;
    }

    //地毯式层层推进，推进1层+1，每层如果有叶子节点，直接返回
    public int minDepthIterative(TreeNode root) {
        if (root == null) {
            return 0;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        int depth = 1;
        queue.add(root);

        while (!queue.isEmpty()) {
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                if (node.left == null && node.right == null) {
                    return depth;
                }
                if (node.left != null) {
                    queue.add(root.left);
                }
                if (node.right != null) {
                    queue.add(root.right);
                }
            }
            depth++;
        }
        return -1;
    }

}
